 
package com.ruhua.java.logic;
 
import com.ruhua.java.bo.GoodsSkuBo;
import com.ruhua.java.dao.GoodsSku;
import com.ruhua.java.dao.OrderGoods;
import com.ruhua.java.dao.Sku;
import com.ruhua.java.dto.OrderDTO;
import com.ruhua.java.dto.SkuInfoDTO;
import com.ruhua.java.exception.NotFoundException;
import com.ruhua.java.exception.TrowException;
import lombok.Getter;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class OrderCheck {

    private OrderDTO orderDTO;
    @Getter
    private List<Sku> SkuList;

    @Getter
    private Map<Long,Integer> orderNumlist;

    public OrderCheck(OrderDTO orderDTO, List<Sku> SkuList){
        this.orderDTO = orderDTO;
        this.SkuList = SkuList;
        this.orderNumlist = setOrderNumlist();
    }

    public Map<Long,Integer> setOrderNumlist() {
        return orderDTO.getJson().stream().collect(Collectors
                .toMap(SkuInfoDTO::getSkuId,SkuInfoDTO::getNum,(a,b)->a));
    }

    public void isOK() {
        BigDecimal serverTotalPrice = new BigDecimal("0");
        List<GoodsSkuBo> goodsSkuBoList = new ArrayList<>();

        this.skuNotOnSale(orderDTO.getJson().size(), this.SkuList.size());

        for (int i = 0; i < this.SkuList.size(); i++) {
            Sku sku = this.SkuList.get(i);
            Long skuId=sku.getId();
            this.checkStock(skuId,sku.getStock(),sku.getGoodsName()); this.checkPrice(skuId,sku.getPrice(),sku.getGoodsName()); if(!orderNumlist.containsKey(skuId)){
                throw new TrowException("规格不存在");
            }
            BigDecimal num=new BigDecimal(orderNumlist.get(skuId).toString());
            serverTotalPrice = serverTotalPrice.add(sku.getPrice().multiply(num));  }
        this.totalPriceIsOk(orderDTO.getTotalPrice(), serverTotalPrice);
    }

    private void totalPriceIsOk(BigDecimal orderTotalPrice, BigDecimal serverTotalPrice) {
        if (orderTotalPrice.compareTo(serverTotalPrice) != 0) {
            throw new TrowException(orderTotalPrice+"订单合计价格错误"+serverTotalPrice);
        }
    }



    private void skuNotOnSale(int count1, int count2) {
        if (count1 != count2) {
            throw new TrowException(count1+"规格错误"+count2);
        }
    }


    private void checkStock(Long id,Long stock,String name) {

        this.orderDTO.getJson().stream().forEach(s->{
            if(s.getSkuId().equals(id)){
                if(s.getNum()>stock){
                    throw new TrowException("商品：" + name + " 库存不足");
                }
            }
        });
    }

    private void checkPrice(Long id,BigDecimal price,String name) {

        this.orderDTO.getJson().stream().forEach(s->{
            if(s.getSkuId().equals(id)){
                if(s.getPrice().compareTo(price)!=0){
                    throw new TrowException("商品：" + name + " 价格错误");
                }
            }
        });
    }
}
